package com.whitedream.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 图片编码工具类
 *
 * @author binge
 */
public class EncodeImgUtil {
    /**
     * 读取文件返回字节数组
     * @param filePath 文件路径
     * @return 字节数组
     */
    public static byte[] readBytesFromFile(String filePath) {
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;
        try {
            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytesArray;
    }

    /**
     * 写入字节数组到文件中
     * @param bytes 字节数组
     * @param filePath 文件路径
     * @throws IOException 异常
     */
    public static void writeBytesToFile(byte[] bytes,String filePath) throws IOException {
        FileOutputStream fos = new FileOutputStream(filePath);
        fos.write(bytes);
        fos.close();
    }

    /**
     * 将图片内容处理成 Base64 编码格式
     *
     * @param filePath 文件路径
     * @return
     */
    public static String encoderImg(String filePath) {
        String fileString = null;
        byte[] imgBytes = null;

        //将文件转化为字节数组
        imgBytes = readBytesFromFile(filePath);

        //将文件字节数组进行 Base64 编码
        BASE64Encoder encoder = new BASE64Encoder();
        fileString = encoder.encode(imgBytes);
        return fileString;
    }

    /**
     * 将Base64 编码格式处理成图片内容
     *
     *
     * @param
     * @param fileString
     * @return
     */
    public static byte[] decoderImg(String fileString) throws IOException {
        byte[] imgBytes = null;
        BASE64Decoder decoder = new BASE64Decoder();
        imgBytes = decoder.decodeBuffer(fileString);
        return imgBytes;
    }
}
